#include "StringTokenizer.h"

StringTokenizer::StringTokenizer(const std::string str,	const std::string delims, bool returnDelimeters){
	m_string = str;
	m_delimeters = delims;
	m_returnDelimeters = returnDelimeters;
	m_stringLength = str.length();
}


bool StringTokenizer::isDelimeter(const char ch){
	int len = m_delimeters.length();
	for(int i = 0; i < len; i++)
		if(ch == m_delimeters.at(i))
			return true;
	return false;
}

bool StringTokenizer::hasMoreTokens(){
	if(m_stringLength <= 1){
		if(m_stringLength == 0)
			return false;
		else if(isDelimeter(m_string.at(0)) && !m_returnDelimeters)
			return false;
	}
	return true;
}

std::string StringTokenizer::nexToken(){
	std::queue<char> st;
	// iterate until it encounters a delimeter
	while(m_stringLength > 0 && !isDelimeter(m_string.at(0))){
		st.push(m_string.at(0));
		m_string = m_string.substr(1, m_stringLength - 1);
		m_stringLength--;
	}

	// if returnDelimeters is true, it will push the delimeter to the stack
	if(st.empty() && m_returnDelimeters && isDelimeter(m_string.at(0))){
		st.push(m_string.at(0));
		m_string = m_string.substr(1, m_stringLength - 1);
		m_stringLength--;
	}

	// else remove the delimeter from the string then call nextToken
	else if(m_stringLength > 0 && !m_returnDelimeters && st.empty()){
		m_string = m_string.substr(1, m_stringLength - 1);
		m_stringLength--;
		return this->nexToken();
	}
	std::string ret = toString(st);
	return ret;
}

std::string StringTokenizer::toString(std::queue<char> &st){
	std::string ret;
	while(!st.empty()){
		char ch[2];
		ch[1] = '\0';
		ch[0] = st.front();
		st.pop();
		ret = ret + std::string(ch);
	}
	return ret;
}
